
// http://127.0.0.1/?ip=192.168.0.&num=40&port=8080
import inquirer from 'inquirer';
import chalk from 'chalk';
import http from 'http';
import axios from 'axios';
export const ipScannerMain = () => {
  console.log('👏欢迎使用局域网扫描工具🔧');
  console.log('检查局域网端口是否可通过HTTP访问');

  inquirer.prompt([
    {
      type: 'input',
      name: 'host',
      message: '请输入要扫描的主机地址：',
      default: '192.168.0.',
    },
    {
      type: 'number',
      name: 'port',
      message: '请输入端口（如：8080）：',
      default: 8080,
      validate: (value) => {
        if (value && value > 0) {
          return true
        } else {
          return '请输入正确的端口号'
        }
      }
    },
    {
      type: 'number',
      name: 'portStart',
      message: '请输入要扫描的端口开始（如：40）：',
      default: 40,
      validate: (value) => {
        if (value && value > 0) {
          return true
        } else {
          return '请输入正确的端口号'
        }
      }
    },
  ]).then(answers => {

    // 用户输入参数
    let num = answers.portStart;
    let port = answers.port;

    // 基础配置
    let baseIP = answers.host;
    const results = []; // 存储最终结果

    // 生成 URL 列表
    const urls = [];
    for (let i = 101; i <= 100 + num; i++) {
      const host = `${baseIP}${i}`;
      const url = port ? `http://${host}:${port}` : `http://${host}`;
      urls.push({ host, url });
    }

    // 超时函数
    function timeoutPromise(url) {
      return new Promise((_, reject) => {
        setTimeout(() => {
          reject(new Error(`Timeout: ${url}`));
        }, 3000); // 3秒超时
      });
    }

    // 发起请求并收集结果
    async function runRequests() {
      for (const { host, url } of urls) {
        try {
          const response = await Promise.race([
            axios.get(url),
            timeoutPromise(url)
          ]);

          results.push({
            host,
            status: 'success',
            statusCode: response.status,
            data: response.data
          });

          console.log(chalk.blue(`${host} success`));
        } catch (error) {
          results.push({
            host,
            status: 'failed',
            error: error.message
          });

          console.error(`${host} failed: ${error.message}`);
        }
      }

      console.log('\nAll Results:', JSON.stringify(results, null, 2));
    }

    runRequests()
    console.log(`🚀 开始扫描 ${baseIP}:${port}- ${baseIP}1 - ${baseIP}1${num}  范围的端口可访问性`);
  })

}